package com.lch.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
 * nio客户端
 *
 * @author: liuchenhui
 * @create: 2019-07-21 14:53
 **/
public class NIOClientDemo {

    private Selector selector = null;
    private static final int port = 8080;
    private ByteBuffer byteBuffer = ByteBuffer.allocate(102400);

    public void init() {
        try {
            selector = Selector.open();
            SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("localhost", port));
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);

            new Thread(() -> {
                try {
                    while (true) {
                        int select = selector.select();
                        if (select <= 0) {
                            continue;
                        }
                        Set<SelectionKey> selectionKeys = selector.selectedKeys();
                        Iterator<SelectionKey> iterator = selectionKeys.iterator();
                        while (iterator.hasNext()) {
                            SelectionKey key = iterator.next();
                            iterator.remove();

                            handleKey(key);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();

            Scanner scan = new Scanner(System.in);
            while (scan.hasNextLine()) {
                String line = scan.nextLine();
                socketChannel.write(ByteBuffer.wrap(line.getBytes()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void handleKey(SelectionKey key) {
        try {
            if (key.isReadable()) {
                SocketChannel socketChannel = (SocketChannel) key.channel();
                StringBuffer content = new StringBuffer();
                if (socketChannel.read(byteBuffer) > 0) {
                    byteBuffer.flip();
                    content.append(new String(byteBuffer.array(), "UTF-8"));
                }
                if (content.length() > 0) {
                    System.out.println("收到回执消息：" + content);
                    key.interestOps(SelectionKey.OP_READ);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        new NIOClientDemo().init();
    }
}
